<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="uploadUrl"
      :headers="headers"
      :show-file-list="false"
      :data="dataObj"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
    >
      <img
        v-if="imageUrl != null && imageUrl !== ''"
        :src="imageUrl"
        width="200px"
        height="200px"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import * as imageConversion from 'image-conversion'

export default {
  name: 'SingleUploadImage',
  props: {
    // 图片属性数组
    value: {
      type: [Number, String],
      default: function() {
        return 0
      }
    },
    // 上传文件类型限制
    fileType: {
      type: String,
      default: 'png|jpg|jpeg|gif|bmp'
    },
    uploadUrl: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/api/admin/file/upload'
    },
    viewUrl: {
      type: String,
      default: process.env.VUE_APP_BASE_API + '/api/admin/file/view/'
    },
    dataObj: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      headers: {
        Authorization: getToken()
      },
      dialogVisible: false,
      dialogImageUrl: null,
      fileList: [],
      image: null
    }
  },
  computed: {
    imageUrl() {
      if (this.value !== 0) {
        return this.viewUrl + this.value
      } else {
        return ''
      }
    }
  },
  created() {
    if (this.value !== 0) {
      this.image = { url: this.viewUrl + this.value, id: this.value }
    } else {
      this.image = null
    }
  },
  methods: {
    emitInput(image) {
      this.$emit('input', image.id)
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.emitInput(fileList)
    },
    handlePreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    beforeUpload(file) {
      const reg = new RegExp(this.fileType, 'i')
      const validate = reg.test(file.type)
      if (!validate) {
        this.$message.error('仅能上传格式是 ' + this.fileType + '的文件!')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10MB!')
        return false
      }
      return new Promise((resolve) => {
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 200).then((res) => {
          resolve(res)
        })
        // 压缩到0.6,这里的0.6就是要压缩的大小,可自定义
        // imageConversion.compress(file,0.6).then(res => {
        //   console.log(res)
        //   resolve(res)
        // })
      })
    },
    handleUploadSuccess(res, file) {
      const attachment = res.data.attachment
      this.image = {
        url: this.viewUrl + attachment.fileAttachmentId,
        name: file.name,
        id: attachment.fileAttachmentId
      }
      this.emitInput(this.image)
    }
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.avatar {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
